<template>
  <el-form :model="form" :rules="rules" ref="ruleFormRef" status-icon :label-position="labelPosition" label-width="120px"
    :inline="true" class="demo-form-inline">

    <el-form-item label="项目名称" prop="projectName">
      <!-- <el-input maxlength="50" v-model="form.projectName" /> -->
      <el-select v-model="form.projectName" placeholder="请选择" @change="projectNameChange" :disabled="disabledFlag">
        <el-option v-for="item in data.nameList" :key="item.projectName" :label="item.projectName" :value="item.id" />
      </el-select>
    </el-form-item>

    <el-form-item label="项目类别" prop="projectCategoryId">
      <el-select v-model="form.projectCategoryId" placeholder="请选择" :disabled="disabledFlag">
        <el-option v-for="item in data.projectCategoryList" :key="item.itemValue" :label="item.itemText"
          :value="item.itemValue" />
      </el-select>
    </el-form-item>

    <el-form-item label="项目开始时间" prop="projectStartTime">
      <el-date-picker v-model="form.projectStartTime" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        :disabled="disabledFlag" @change="handleChangeDate0" />
    </el-form-item>

    <el-form-item label="预计完成时间" prop="projectEndTime">
      <el-date-picker v-model="form.projectEndTime" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        :disabled="disabledFlag" @change="handleChangeDate1" />
    </el-form-item>

    <el-form-item label="申报单位" prop="applyUnit">

      <popup-tree-input :data="orgAllList" :props="data.popupTreeProps" :prop="deptForm.parentName == null
          ? $t('message.org.top_menu')
          : form.applyUnit
        " :node-key="'' + deptForm.parentId" :current-change-handle="changeUnit" clearable />

    </el-form-item>

    <el-form-item label="总资产（万元）" prop="totalBudget">
      <el-input  v-model="form.totalBudget" :disabled="disabledFlag"
                 maxlength="16"
                 :onkeypress="($event) => /[\d]/.test(String.fromCharCode($event.keyCode))"
                 clearable />
    </el-form-item>

    <el-form-item label="申报日期" prop="applyDate">
      <el-date-picker v-model="form.applyDate" format="YYYY-MM-DD" type="date" placeholder="选择日期" clearable
        :disabled="disabledFlag" @change="handleChangeDate2" />
    </el-form-item>


    <el-form-item label="概述（项目背景、编制依据、项目范围、建设目标、主要建设内容）" style="width: 100%">
      <el-input v-model="form.summarize" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"   show-word-limit  />
    </el-form-item>

    <el-form-item label="现状及需求分析" style="width: 100%">
      <el-input v-model="form.demandAnalysis" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"  show-word-limit  />
    </el-form-item>

    <el-form-item label="项目必要性和可行性分析" style="width: 100%">
      <el-input v-model="form.feasibilityNalysis" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"   show-word-limit />
    </el-form-item>

    <el-form-item label="项目内容和实施方案" style="width: 100%">
      <el-input v-model="form.implementationPlan" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"  show-word-limit />
    </el-form-item>

    <el-form-item label="项目计划进度" style="width: 100%">
      <el-input v-model="form.projectSchedule" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"  show-word-limit />
    </el-form-item>

    <el-form-item label="项目费用估算" style="width: 100%">
      <el-input v-model="form.projectCostEstimation" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入"  show-word-limit />
    </el-form-item>

    <el-form-item label="项目效益分析（经济效益、社会效益、管理效益）" style="width: 100%">
      <el-input v-model="form.projectBenefitAnalysis" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入" show-word-limit  />
    </el-form-item>

    <el-form-item label="风险及对策" style="width: 100%">
      <el-input v-model="form.riskCountermeasure" :autosize="{ minRows: 2 }" maxlength="2000" type="textarea"
        :disabled="disabledFlag" placeholder="请输入" show-word-limit  />
    </el-form-item>
    <el-form-item label="上传附件" style="width: 100%">
<!--
      <el-upload ref="uploadRef" :limit="1" :headers="headers" action="/fastDfs/file/upload"
        :on-success="handleApplication" :show-file-list="true">
        <el-button type="primary" :disabled="disabledFlag">点击上传</el-button>
      </el-upload>
      <a class="document-link" target="_blank" v-if="store.state.lxsq.lxsqInfo.approvalFilePath"
        :href="store.state.lxsq.lxsqInfo.approvalFilePath">文件链接</a>
-->
      <el-upload
        ref="uploadRef"
        :limit="5"
        :headers="headers"
        action="/fastDfs/file/upload"
        :on-success="handleStandard"
        :on-preview="previewFile"
        :on-remove="removeRdForm"
        :on-exceed="handleExceed"
        :on-error="handleError"
        :file-list="form.approvalFilePath || []"
        :disabled="disabledFlag"
        drag
    ><!--:on-success="handleAttachment"--><!--        v-model:file-list="data.approvalFilePath"-->

      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <div class="el-upload__tip"></div>
    </el-upload>

    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import { ElMessage } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
import { getName } from '../../api/szhlxsp'
import SelectOption from '../components/selectOption/index.vue'
import {type} from "@/utils/utils";

export default {
  components: {
    SelectOption,PopupTreeInput
  },
  emits: {
    valueFlag: null,
  },
  props: {
    disabledFlag: {
      type: Boolean
    },
    orgAllList: {
            type: Array,
            required: true,
        },
  },
  setup(props, { emit }) {
    const store = useStore()
    const labelPosition = ref('top')
    const deptForm = {
            parentId: 0,
            parentName: '',
        }

    const data = reactive({
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
      activeName: ref('first'),
      addUnit: false,
      innerValue: '',
      outsideValue: '',
      levelOptions: computed(() => store.state.innovativeTalents.cxlevelSelect),
      typeOptions: [],

      researchSelect: computed(() => store.state.innovativeTalents.businessList),
      stateSelect: computed(() => store.state.innovativeTalents.tdStatue),

      userAllList: computed(() => store.state.technologyStrength.userAllList),
      orgAllList: [],

      nameList: [{ projectName: '', id: '' }],
      projectCategoryList: [{ itemValue: '', itemText: '' }],//项目列表下拉
    })

    const form = store.state.lxsq.lxsqInfo
    watch(form, (newValue, oldValue) => {
      console.log('watch', form);
      store.commit('lxsq/lxsqInfo', { ...form })
    });
    if (form.teamLevelId) {
      data.levelOptions.map((item) => {
        if (item.itemValue == form.teamLevelId) {
          data.typeOptions = item.children
        }
      })
    }

    const changeValue = (item) => {
      form.projectCategory = item.name
      form.projectCategoryId = item.id
    }
    const changeValue1 = (item) => {
      form.managerName = item.username
      form.managerId = item.userId
    }
    const changeValue2 = (item) => {
      form.teamLevel = item.itemText
      form.teamLevelId = item.itemValue
      data.typeOptions = item.children
      form.teamClass = ''
      form.teamClassId = ''
    }
    const changeValue3 = (item) => {
      form.teamClass = item.itemText
      form.teamClassId = item.itemValue
    }
    const changeValue4 = (item) => {
      form.techFieldName = item.itemText
      form.techFieldId = item.itemValue
    }


    const pickerOptionsStart = (rule, value, callback) => {
      if (value) {
        if (new Date(form.projectStartTime).getTime() > new Date(form.projectEndTime).getTime()) {
          return callback(new Error("开始时间不能大于结束时间"))
        } else {
          return callback()
        }
      } else {
        return callback(new Error("开始时间不能为空"));
      }
    }
    const pickerOptionsEnd = (rule, value, callback) => {
      if (value) {
        if (new Date(form.projectStartTime).getTime() > new Date(form.projectEndTime).getTime()) {
          return callback(new Error("结束时间不能小于开始时间"))
        } else {
          return callback()
        }
      } else {
        return callback(new Error("结束时间不能为空"));
      }
    }

    const rules = reactive({
      projectName: [
        { required: true, message: '请输入项目名称', trigger: 'blur' },
      ],
      projectCategoryId: [
        { required: true, message: '请选择项目类别', trigger: 'change', },
      ],
      // projectCategory: [
      //   { required: true, message: '请选择项目类别', trigger: 'change', },
      // ],
      // projectStartTime: [
      //   { required: true, message: '请选择项目开始时间', trigger: 'change', },
      // ],
      applyUnit: [
        { required: true, message: '请选择申报单位', trigger: 'change', },
      ],

      totalBudget: [
        { required: true, message: '请输入总资产', trigger: 'blur' },
      ],
      applyDate: [
        { required: true, message: '请选择申报日期', trigger: 'change' },
      ],
      projectStartTime: [{ required: true, validator: pickerOptionsStart, trigger: "change" }],
      projectEndTime: [{ required: true, validator: pickerOptionsEnd, trigger: "change" }],
    })

    const ruleFormRef = ref()
    const submitForm = async () => {
      await ruleFormRef.value.validate((valid, fields) => {
        if (valid) {
          emit('valueFlag', true)
          console.log('submit!')
        } else {
          emit('valueFlag', false)
          console.log('submit false!')
        }
      })
    }

    let changeUnit=(item)=>{

      form.applyUnitId=item.id
      form.applyUnit=item.name

    }

    const handleChangeDate0 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.projectStartTime = formattedDate
      store.commit('lxsq/lxsqInfo', { ...form })
    }
    const handleChangeDate1 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.projectEndTime = formattedDate
      store.commit('lxsq/lxsqInfo', { ...form })
    }
    const handleChangeDate2 = (val) => {
      const year = val.getFullYear(); // 获取年份
      const month = (val.getMonth() + 1) < 10 ? '0' + (val.getMonth() + 1) : (val.getMonth() + 1); // 获取月份，需要加1
      const day = val.getDate() < 10 ? '0' + val.getDate() : val.getDate(); // 获取日期
      const formattedDate = `${year}-${month}-${day}`;
      form.applyDate = formattedDate
      store.commit('lxsq/lxsqInfo', { ...form })
    }
    //获取项目名称下拉框
    const getName1 = () => {
      getName().then(res => {
        // console.log('res',res);
        data.nameList = res.data.data
      })
    }
    const projectNameChange = (val) => {
      console.log('projectNameChange', val);
      form.projectId = val
    }
    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: ["KHGL_XMZL_KJ_TYPE"]

      }).then((res) => {
        console.log('字典', res);
        data.projectCategoryList = res.data.data.KHGL_XMZL_KJ_TYPE
      })
    }
    //-----------文件上传---------
    const handleDocument = (uploadFile, key) => {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        store.state.lxsq.lxsqInfo[key] = uploadFile.data.path
        form.approvalFileName = uploadFile.data.fileName
        form.approvalFilePath = uploadFile.data.path
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    }
    const handleApplication = (uploadFile) => {
      handleDocument(uploadFile, 'projectApplication')
    }

    const previewFile = (file) => {
      window.open(file.url)
    }

    const removeRdForm = (file, uploadFiles) => {
      handleRemove(file, uploadFiles, 'approvalFilePath')
    }
    const handleRemove = (file, uploadFiles, key) => {
      form.approvalFilePath = form.approvalFilePath.filter(o => o.url !== file.url);
    }
    const handleExceed = () => {
      ElMessage({
        message: '最多上传5个附件',
        type: 'wraning',
      })
    }
    const handleError = () => {
      ElMessage({
        message: '上传失败',
        type: 'error',
      })
    }
    const handleStandard = (uploadFile) => {
      if (uploadFile.code == 200) {
        ElMessage({
          message: '上传成功',
          type: 'success',
        })
        console.log('上传成功uploadFile', uploadFile)
        let obj = {
          name: uploadFile.data.fileName,
          url: uploadFile.data.path,
        }
        form.approvalFilePath = (form.approvalFilePath || []).concat(obj)
      } else {
        ElMessage({
          message: '上传失败',
          type: 'error',
        })
      }
    }


    getName1()
    affiliation()
    const cookie = () => localStorage.getItem('token')
    return {
      labelPosition,
      data,
      store,
      form,
      rules,
      ruleFormRef,
      changeUnit,
      submitForm,
      handleChangeDate0,
      handleChangeDate1,
      handleChangeDate2,

      changeValue,
      changeValue1,
      changeValue2,
      changeValue3,
      changeValue4,
      getName1,
      projectNameChange,
      headers: {
        Authorization: 'Bearer ' + cookie(),
      },
      handleApplication,
      deptForm,
      previewFile,
      handleExceed,
      handleError,
      removeRdForm,
      handleStandard,
    }
  },
}
</script>
<style lang="scss" scoped> .split-line {
   display: flex;
   flex-direction: column;
   margin-bottom: 10px;
 }

 .demo-form-inline .el-form-item {
   width: 48%;
 }

 :deep(.labelHeight .el-form-item__label) {
   line-height: 20px;
 }

 :deep(.el-date-editor.el-input) {
   width: 100%;
 }

 :deep(.el-date-editor.el-input__inner) {
   width: 100%;
 }

 :deep(.demo-form-inline .el-select) {
   width: 100%;
   margin: 0;
 }

 .el-select {
   width: 100%;
   margin: 0;
 }

 .selectLabel {
   width: 70%;
   min-height: 40px;
   line-height: 40px;
   padding: 0 15px;
   border: 1px solid #ccc;
   border-radius: 6px;
   display: inline-block;
 }

 .addLabel {
   display: inline-block;
   width: 120px;
   height: 30px;
   line-height: 30px;
   text-align: center;
   background-color: #169bd5;
   border-radius: 6px;
   color: #fff;
   margin-left: 15px;
 }

 .unitBox {
   width: 100%;
   margin: 30px 0;

   .title {
     padding: 15px 0;
     border-bottom: 1px solid #ccc;
   }

   .tagBox {
     line-height: 40px;
     margin-top: 15px;
     border: 1px solid #ccc;
     border-radius: 8px;
     padding: 10px 15px;
   }
 }

 .el-tag {
   margin-right: 10px;
 }
</style>
